<!--
 * @Descripttion: unTitle
 * @Author: yizheng.yuan
 * @Date: 2021-11-28 10:50:05
 * @LastEditors: yizheng.yuan
 * @LastEditTime: 2021-11-29 09:11:37
-->
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
  <title>Document</title>
  <link rel="stylesheet" type="text/css" href="./css/reset.css" />
  <link rel="stylesheet" type="text/css" href="./css/my-reset.css" />
  <link rel="stylesheet" type="text/css" href="./css/pd-mg.css" />
  <style>
    .warp_one {
      height: 100vh;
      display: flex;
      flex-direction: column;
    }

    .head {
      height: 200px;
      background-color: #0f59a4;
      text-align: center;
    }

    .headIcon {
      width: 100px;
      height: 100px;
      border-radius: 50%;
      margin: 30px auto;
      background-size: 100% 100%;
    }

    .openId {
      color: #fff;
      font-size: 16px;
      font-weight: bold;
    }

    .main {
      flex: 1;
      background-color: #eff3f6;
    }

    .searchBox {
      background-color: #fff;
      padding: 20px;
      box-shadow: 0 8px 15px #ccc;
      border-bottom: 1px solid #ddd;
    }

    .input-default,
    .button-default {
      width: 100%;
      height: 45px;
      line-height: 45px;
      border: 1px solid #ddd;
      border-radius: 3px;
      padding: 0 5px;
      font-size: 16px;
    }

    .button-default {
      text-align: center;
      border: none;
      background-color: #0f59a4;
      color: #fff;
      font-size: 16px;
    }

    .resultBox {
      padding: 15px 20px;
      border: 1px solid #eee;
      background-color: #fff;
      color: #010101;
      font-weight: bold;
      font-size: 12px;
      border-radius: 5px;
      box-shadow: 0 8px 25px #aaa;
    }

    .resultBox li {
      height: 40px;
      line-height: 40px;
      border-bottom: 1px solid #f2f2f2;

    }

    .noResultBox {
      text-align: center;

    }

    .imgBox {
      margin: 10px auto;
    }

    .imgBox img {
      width: 100px;
      height: 100px;
    }

    .theme-blue {
      color: #0f59a4;
    }

    .theme-gray {
      color: #9c9e9d;
    }

    .theme-black {
      color: #010101;
    }
  </style>
  <link rel="stylesheet" type="text/css" href="./css/element-ui.css" />
</head>

<body>
  <div class="warp_one" id="app">
    <div class="head">
      <div class="headIcon" v-if="userInfo && userInfo.headimgurl"
        :style="{backgroundImage:`url(${userInfo.headimgurl})`}">
      </div>
      <p class="openId" v-if="userInfo">ID:{{userInfo.openid}}</p>
    </div>
    <div class="main">
      <div class="searchBox">
        <p><input class="input-default" placeholder="请输入您的身份证号" v-model="myObj.myId" /></p>
        <div class="flexBox-r">
          <button class="button-default mg-t20 flex1 mg-r10" @click="channelFun(0)">通道1</button>
          <button class="button-default mg-t20 flex1 mg-l10" @click="channelFun(1)">通道2</button>
        </div>
      </div>
      <div class="pd20" v-if="hasSearch">
        <div class="resultBox" v-if="!finishBind">
          <div v-if="!resultObj" class="noResultBox">
            <div class="imgBox"><img src="./images/notFount.png"></div>
            <p class="theme-gray mg-t15 font16 font-l">未查询到相关信息</p>
          </div>
          <div v-else>
            <ul>
              <li class="font16">{{resultObj.companyName}}</li>
              <li>姓名：{{resultObj.name}}</li>
              <li>手机号：<span class="theme-blue">{{resultObj.telephone}}</span></li>
            </ul>
            <p><button class="button-default mg-t20" @click="bindFun">绑 定</button></p>
          </div>
        </div>
        <div v-else class="text-c mg-t5 theme-gray"> 已完成绑定 </div>
      </div>
    </div>
  </div>

  <script src="./js/vue.min.js"></script>
  <script src="./js/axios.min.js"></script>
  <script src="./js/element-ui.js"></script>
  <script>
    const local = window.location.href
    var iconUrl = 'http://localhost/html/demo.png';

    // 服务器地址
    var serverUrl = 'http://7f55-61-140-181-220.ngrok.io';

    // 回调地址：要将回调地址的域名加到微信公众平台
    var redirect_uri = window.location.href;

    var wxConfig = {
      appId: 'wx3680aee5b396cc0f',
      // appId: 'wxcfb89a4c06dd77ec',
      appsecret: '626c988a2e4af8cc459424187951792e',
      token: 'fsadfsdfd978466545654',
      scope: 'snsapi_userinfo'
    }

    var snsapi_base_Url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${wxConfig.appId}&redirect_uri=${encodeURIComponent(redirect_uri)}&response_type=code&scope=${wxConfig.scope}&state=123#wechat_redirect`;
    var vm = new Vue({
      el: '#app',
      data: {
        hasSearch: false,
        finishBind: false,
        userInfo: null,
        myIcon: iconUrl,
        myObj: {
          myId: '152631200005080918'
        },
        openId: "WERdfdfg3434dssfsdfsq",
        resultObj: {
          companyName: '山东侨联智能科技有限公司',
          name: '',
          telephone: '13631338856'
        }
      },
      mounted() {
        // this.getRight()
        // 如果本地有openId就不用请求了
        this.userInfo = JSON.parse(window.localStorage.getItem('userInfo'))
        console.log('this.userInfo', this.userInfo);
        if (!this.userInfo || this.userInfo.openId) {
          // this.getCode()
        } else {
          // this.getUserInfo()
        }
      },
      methods: {
        async bindFun() {
          let url = `http://qiaolianyun.viphk.91tunnel.com/health/bind`;
          let data = {
            "name": this.resultObj.name,
            "companyName": this.resultObj.name,
            "idNumber": this.myObj.myId,
            "openId": this.userInfo.openid
          }
          try {
            let rel = await this.postData(url, data);
            console.error('绑定结果',rel);
            this.$message({
              message: '绑定成功！',
              type:'success'
            })
            this.finishBind = true;
          } catch (error) {
            console.error('绑定出错',error);
            this.$message({
              message: '绑定出错！',
              type:'error'
            })
          }
          
        },
        async channelFun(channelName) {
          this.hasSearch = true;
          if (!channelName) {
            let url = `http://qiaolianyun.viphk.91tunnel.com/health/select/${this.myObj.myId}`;
            try {
              let rel = await this.getData(url);
              console.log('通道结果1：', rel);
              this.resultObj = rel.data;
            } catch (error) {
              console.error('error:', error);
            }
          } else {
            let url = `http://qiaolianyun.viphk.91tunnel.com/health/newTable/${this.myObj.myId}`;
            let rel = await this.getData(url);
            console.log('通道结果2：', rel);
            this.resultObj = rel.data;
          }
        },
        async getUserInfo() {
          let url = `https://api.weixin.qq.com/sns/userinfo?access_token=${this.userInfo.access_token}&openid=${this.userInfo.openid}&lang=zh_CN`
          try {
            let rel = await this.getData(url)
            console.log('用户信息：', rel);
          } catch (error) {
            console.error('拉取用户信息错误：', error);
          }
        },
        postData(url, data) {
          return new Promise((resolve, reject) => {
            axios.post(url, data)
              .then(res => {
                resolve(res)
              })
              .catch(err => {
                reject(err)
              })
          })
        },
        getData(url) {
          return new Promise((resolve, reject) => {
            axios.get(url)
              .then(res => {
                resolve(res)
              })
              .catch(err => {
                reject(err)
              })
          })
        },
        getCode() {
          const code = this.getUrlParam('code')  // 截取路径中的code
          if (code == null || code === '') {
            console.error('跳转授权11：');
            window.location.href = snsapi_base_Url;
            // window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=' + encodeURIComponent(local) + '&response_type=code&scope=snsapi_base&state=1#wechat_redirect';
          } else {
            console.error('获取到的code:', code);
            this.getRight(code)
            // this.getOpenId(code) //把code传给后台获取用户信息
          }
        },
        getUrlParam(name) {
          var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
          let url = window.location.href.split('#')[0]
          let search = url.split('?')[1]
          if (search) {
            var r = search.substr(0).match(reg)
            if (r !== null)
              return unescape(r[2])
            return null
          } else
            return null
        },
        getRight(code) {
          let that = this;
          // var url = `${serverUrl}/code`
          var url = `${serverUrl}/getUserInfo`
          let data = { code };
          axios.post(url, data)
            .then(res => {
              console.log('code数据：', res);
              that.userInfo = res.data;
              window.localStorage.setItem('userInfo', JSON.stringify(res.data))
            })
            .catch(err => {
              console.error('err:', err);
            })
        }
      }
    })
  </script>
</body>

</html>